package com.dxy.hms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dxy.hms.base.UnifiedException;
import com.dxy.hms.model.entity.Role;
import com.dxy.hms.mapper.RoleMapper;
import com.dxy.hms.mapper.RoleMenuMapper;
import com.dxy.hms.mapper.UserRoleMapper;
import com.dxy.hms.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;

/**
* <p>
* 角色表 服务实现类
* </p>
*
* @author dxy
* @since 2024-09-24
*/
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public void add(Role entity) {
        if (baseMapper.selectCount(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, entity.getRoleCode()))>0){
            throw new UnifiedException(500, "角色编码{}已存在", entity.getRoleCode());
        }
        baseMapper.insert(entity);
    }

    @Override
    public void updById(Role entity) {
        baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public void delByIds(List<Long> ids) {
        // 删除角色
        baseMapper.deleteBatchIds(ids);
        // 删除用户角色关联关系
        ids.forEach(id -> userRoleMapper.delByRoleId(id));
        // 删除角色菜单关联关系
        ids.forEach(id -> roleMenuMapper.delByRoleId(id));
    }

    @Override
    public Role getDetail(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public IPage<Role> getPage(String roleCode, String roleName, Long pageNum, Long pageSize) {
        if (pageNum == null || pageNum <= 0) { pageNum = 1L; }
        if (pageSize == null || pageSize <= 0) { pageSize = 10L; }
        IPage<Role> page = new Page<>(pageNum, pageSize);
        Wrapper<Role> wrapper = new LambdaQueryWrapper<Role>()
                .like(StrUtil.isNotEmpty(roleCode), Role::getRoleCode, roleCode)
                .like(StrUtil.isNotEmpty(roleName), Role::getRoleName, roleName)
                .orderByDesc(Role::getCreateTime);
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public List<Role> getList(String roleName) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(roleName), Role::getRoleName, roleName);
        wrapper.orderByDesc(Role::getCreateTime);
        return baseMapper.selectList(wrapper);
    }

}
